#include "shutdown_handler.h"
#include "shutdown_callback.h"
#include "debug.h"
#include "error.h"
#include "logging.h"
#include "reactor.h"
#include "scoped_ptr.h"
#include "utils.h"
#include "const_object_names.h"

ShutdownHandler::ShutdownHandler() : shutdown_callback_(NULL)
{
}

ShutdownHandler::~ShutdownHandler()
{
	if (get(shutdown_event_))
		VERIFY1(SUCCEEDED(reactor_->UnregisterHandler(get(shutdown_event_))));
}

HRESULT ShutdownHandler::Initialize(Reactor* reactor, 
									ShutdownCallback* shutdown, 
									bool is_machine)
{
	ASSERT1(reactor);
	ASSERT1(shutdown);

	shutdown_callback_ = shutdown;
	reactor_ = reactor;
	is_machine_ = is_machine;

	NamedObjectAttributes attr;
	GetNamedObjectAttributes(kShutdownEvent, is_machine_, &attr);
	// Namual reset = true and signaled = false
	reset(shutdown_event_, ::CreateEvent(&attr.sa, true, false, attr.name));
	if (!shutdown_event_)
		return HRESULTFromLastError();

	HRESULT hr = reactor_->RegisterHandle(get(shutdown_event_), this, 0);
	if (FAILED(hr))
		return hr;

	return S_OK;
}

void ShutdownHandler::HandleEvent(HANDLE handle)
{
	if (handle == get(shutdown_event_))
		CORE_LOG(L1, (_T("[shutdown event is signaled]")));
	else 
		ASSERT1(false);
	ASSERT1(shutdown_callback_);
	shutdown_callback_->Shutdown();
}